<template>
    <el-dialog :visible.sync="isShow" :title="headerTitle" @close="handleClose" center top="14vh" width="60%" append-to-body :fullscreen="fullscreen">
        <el-form :model="dialogForm" size="small" :disabled="type==3" label-suffix=":" ref="detailForm" :rules="rules" label-width="100px">
            <el-row>
                <el-col :span="24">
                    <!--            用户事业部-->
                    <el-form-item :label="$t('inspectionStandards.division')" prop="divisionName">
                        <el-select v-model="dialogForm.divisionName" size="small" @change="handleDivisionChange">
                            <el-option v-for="item in divisionList" :key="item" :label="item" :value="item">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <!--            物料大类-->
                    <el-form-item :label="$t('basicData.MaterialCategory')" prop="categoryName">
                        <el-select v-model="dialogForm.categoryName" filterable size="small" @change="handlecategoryChange" :placeholder="$t('public.selectPl')+'物料大类'">
                            <el-option v-for="item in materialList" :key="item.label" :label="item.label" :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <!--            检验项大类-->
                    <el-form-item :label="'检验项大类'" prop="projectType">
                        <el-select v-model="dialogForm.projectType" filterable size="small" @change="handleDictProjectTypeChange" reserve-keyword :placeholder="$t('public.selectPl')+'检验项大类'">
                            <el-option v-for="item in dict.type.NYIQC_PROJECT_TYPE" :key="item.label" :label="item.label" :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <!--            报告展示内容-->
                    <el-form-item :label="'报告展示内容'" prop="content">
                        <el-input v-model="dialogForm.content" type="textarea" :rows="10" placeholder="请输入内容"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
             

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small">{{$t('public.save')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
import {listAllMaterialMessageMessage} from '@/api/basic/gaugeMessage'
import {addMaterialMessage, updateMaterialMessage,} from '@/api/basic/materialMessage'
import {listALLFactory} from '@/api/basic/factory'
import EnjoySelectUser from '@/components/EnjoySelectUser'
import EnjoySelectDeptTree from '@/components/EnjoySelectDeptTree'
import FileUploadInput from '@/components/FileUploadInput'
import {getMasterialMaxMinData} from '@/api/basic/materialtype'
import {userDivisionNames,getOneLevelCategoryByDivisionName} from '@/api/masterdata/division'
import {addfixedSample,putfixedSampleList} from '@/api/basic/fixedSampling'
export default {
    name: 'mtool-detial',
    components: { EnjoySelectUser, EnjoySelectDeptTree, FileUploadInput },
    dicts: [  
        'QC_MASTERDATA__MATERIAL_LEVEL','NYIQC_PROJECT_TYPE'
    ],
    props: {
        value: {
            type: Object,
        },
        visible: {
            type: Boolean,
            default: false,
        },
        type: [String, Number], //1:新增  2：编辑 3：查看
    },
    watch: {
        value(val) {
            this.dialogForm = { ...val }
        },
    },
    computed: {
        isShow: {
            get() {
                return this.visible
            },
            set() {},
        },
        headerTitle() {
            const { type } = this
            let title = ''
            if (type == 1) {
                title =
                    this.$t('public.add') +
                    ' ' +
                    '固定抽样内容'
            }
            if (type == 2) {
                title =
                    this.$t('public.edit') +
                    ' ' +
                    '固定抽样内容'
            }
            // if(type == 3){
            //   title = this.$t('mtool.viewHeader')
            // }
            return title
        },
    },
    data() {
        return {
            divisionList:[],
            materialList:[],
            loading: false,
            fullscreen: false,
            deviceOptions: undefined,
            factoryOptions: [],
            dialogForm: {},
            // 表单校验
            rules: {
                divisionName: [
                    {
                        required: true,
                        message: '事业部不能为空',
                        trigger: 'blur',
                    },
                ],
                categoryName: [
                    {
                        required: true,
                        message: '物料大类不能为空',
                        trigger: 'blur',
                    },
                ],
                projectType: [
                    {
                        required: true,
                        message: '检验项大类不能为空',
                        trigger: 'blur',
                    },
                ],
                content: [
                    {
                        required: true,
                        message: '报告内容不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            materialMaxOptions: [],
            materialOptions: [
                {value:"1",label:"主材"},
                {value:"2",label:"辅材"}
            ],
            materialMiddleOptions: [],
        }
    },
    mounted() {
        // this.getMaterialType({}, 'materialMax')
        // this.getMaterialType({ materialMax: 'all' }, 'materialMiddle')
        // this.getMaterialType({ materialMiddle: 'all' }, 'typeName')
        this.factoryRemoteMethod()
        this.dialogForm = { ...this.value }
        this.getdivisionList()
    },
    methods: {
        handleDivisionChange(val){
            this.getmaterialList(val)
        },
        handlecategoryChange(val){
            for (const iterator of this.materialList) {
                if(iterator.label == val){
                    this.dialogForm.categoryId = iterator.id
                }
            }
        },
        handleDictProjectTypeChange(val){
            console.log(val,this.dict.type.NYIQC_PROJECT_TYPE)
            for (const iterator of this.dict.type.NYIQC_PROJECT_TYPE) {
                if(iterator.label == val){
                    this.dialogForm.projectTypeDictCode = iterator.raw.dictCode
                }
            }
        },
        getmaterialList(val){
            getOneLevelCategoryByDivisionName({divisionName:val}).then(res => {
                this.materialList = res
            })
        },
        getdivisionList(){
            userDivisionNames().then(res => {
                this.divisionList = res
            })
        },
        changeFactory(dict) {
            
            this.dialogForm.plantName = dict.plantName
            this.dialogForm.plantCode = dict.plantCode
        },
        loadNumber(event) {
            let elValue = event
            let reg = /^((?!0)\d{1,2}|100)$/
            if (!elValue.match(reg)) {
                this.$set(this.dialogForm, 'percentPass', '')
                return false
            } else {
                return true
            }
        },
        getMaterialType(params, name) {
            let array = []
            getMasterialMaxMinData(params).then((res) => {
                array = res.data.map((item) => item[name])
                if (name === 'materialMax') {
                    this.materialMaxOptions = array
                } else if (name === 'materialMiddle') {
                    this.materialMiddleOptions = array
                } else {
                    this.materialOptions = array
                }
            })
        },
        /** 发起提交 */
        submitForm: function () {
            this.loading = true
            this.$refs.detailForm.validate((valid) => {
                let action =
                    this.type == 1 ? addfixedSample : putfixedSampleList
                if (valid) {
                    action(this.dialogForm).then((res) => {
                        this.loading = false
                        if (res.code == 200) {
                            this.$emit('refresh')
                            this.$modal.msgSuccess('操作成功!')
                            this.$emit('update:visible', false)
                        } else {
                            this.$modal.msgError(res.msg)
                            this.loading = false
                        }
                    })
                } else {
                    this.loading = false
                }
            })
        },
        insectionChangeValue() {},
        handleClose(done) {
            this.dialogForm = {}
            this.$refs['detailForm'].clearValidate()
            this.$emit('update:visible', false)
        },
        //设备模糊查询
        deviceRemoteMethod(val, cb) {
            console.log(val)
            listAllMaterialMessageMessage({ deviceName: val }).then((res) => {
                this.deviceOptions = res.data.map((i) => i.deviceName)
                cb(res.data)
            })
        },
        handleDeviceSelect(e) {
            this.dialogForm.deviceName = e.deviceName
            this.dialogForm.gaugeType = e.gaugeType
            this.$refs.deviceName.$emit('el.form.blur')
        },
        handleDeviceBlur(e) {
            const { deviceOptions, dialogForm } = this
            if (!deviceOptions.includes(dialogForm.deviceName)) {
                this.dialogForm.deviceName = ''
            }
        },
        //工厂模糊查询
        factoryRemoteMethod(val, cb) {
            listALLFactory({ factoryName: '' }).then((res) => {
                this.factoryOptions = res.data
            })
        },
        handleMaterialMaxChange(e) {
            this.getMaterialType({ materialMax: e || 'all' }, 'materialMiddle')
            if (this.dialogForm.materialMiddle) {
                this.$set(this.dialogForm, 'materialMiddle', '')
            }
            if (this.dialogForm.materialType) {
                this.$set(this.dialogForm, 'materialType', '')
            }
        },
        handleMaterialMiddleChange(e) {
            this.getMaterialType({ materialMiddle: e || 'all' }, 'typeName')
            if (this.dialogForm.materialType) {
                this.$set(this.dialogForm, 'materialType', '')
            }
        },
        handleFactorySelect(e) {
            this.dialogForm.plantName = e.plantName
            this.$refs.plantName.$emit('el.form.blur')
        },
        handleFactoryBlur(e) {
            const { factoryOptions, dialogForm } = this
            if (!factoryOptions.includes(dialogForm.plantName)) {
                this.dialogForm.plantName = ''
            }
        },
        handleExpireTime(e) {
            console.log(e)
            const today = new Date().getTime()
            const val = new Date(e).getTime()
            if (val > today) {
                this.dialogForm.remDay = ~~(
                    (val - today) /
                    1000 /
                    60 /
                    60 /
                    24
                ).toFixed(1)
            } else {
                this.dialogForm.remDay = 0
            }
            this.$forceUpdate()
        },
        handleRespName(e) {
            this.dialogForm.respName = e.name
        },
        handleEmployName(e) {
            this.dialogForm.employName = e.name
        },
        handleRespDept(e) {
            this.dialogForm.respDept = e.name
        },
    },
}
</script>

<style scoped>
</style>
